<template>
  <x-dialog :title="title" :show.sync="visible" v-if="visible" :before-close="handleClose" width="50%">
    <el-form :model="params" :rules="rules" ref="applicationForm" class="demo-form-inline" label-position="top">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item :label="$t('system.application.id')" prop="clientId">
            <el-input
              v-model="params.clientId"
              :placeholder="$t('system.application.placeholderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.name')" prop="clientName">
            <el-input
              v-model="params.clientName"
              :placeholder="$t('system.application.placeholderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="!params.hasOwnProperty('id')">
          <el-form-item :label="$t('system.application.pwd')" prop="clientSecret">
            <el-input
              v-model="params.clientSecret"
              :placeholder="$t('system.application.placeholderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.pwdTimes')" prop="clientSecretExpiresAt">
            <el-date-picker
              v-model="params.clientSecretExpiresAt"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              style="width: 100%"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.authType')" prop="authorizationGrantTypes">
            <x-select
              :placeholder="$t('system.application.placeholderSelect')"
              :multiple="true"
              :collapseTags="false"
              v-model="params.authorizationGrantTypes"
              :options="dictOptions['upms_registered_client.authorization_grant_types']"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.authMenthods')" prop="clientAuthenticationMethods">
            <x-select
              :placeholder="$t('system.application.placeholderSelect')"
              v-model="params.clientAuthenticationMethods"
              :multiple="true"
              :collapseTags="false"
              :options="dictOptions['upms_registered_client.client_authentication_methods']"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.authScope')" prop="scopes">
            <el-input
              v-model="params.scopes"
              :placeholder="$t('system.application.placeholderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.token')" prop="accessTokenValidity">
            <el-input
              v-model="params.accessTokenValidity"
              :placeholder="$t('system.application.placeholderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.refresh')" prop="refreshTokenValidity">
            <el-input
              v-model="params.refreshTokenValidity"
              :placeholder="$t('system.application.placeholderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.callbackAddress')" prop="redirectUris">
            <el-input
              v-model="params.redirectUris"
              :placeholder="$t('system.application.placeholderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="$t('system.application.clientImg')" prop="clientImg">
            <x-upload
              ref="fileUpload"
              :edit-flag="true"
              :limit="1"
              :fileSize="2"
              :span="24"
              :isFileRemark="false"
              :old-file-list="params.filesList"
              :file-type="['jpg', 'jpeg', 'png']"
              :tips="'支持上传PNG/JPG/jpeg形式文件,附件大小不超过2MB.'"
            >
            </x-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.isAuth')" prop="autoapprove">
            <el-switch
              v-model="params.autoapprove"
              active-color="#4474F6"
              inactive-color="#A5A9B2"
              :active-value="'true'"
              :inactive-value="'false'"
            >
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.state')" prop="state">
            <x-radio-group :listData="dictOptions['system.state']" v-model="params.state"></x-radio-group>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item :label="$t('system.application.resourceList')" prop="noticeTitle">
            <el-input
              v-model="params.noticeTitle"
              :placeholder="$t('system.application.placeholderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.application.auth')" prop="authorities">
            <el-input
              v-model="params.authorities"
              :placeholder="$t('system.application.placeholderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        -->
        <!-- <el-col :span="24">
          <el-form-item :label="$t('system.application.appendRemark')" prop="additionalInformation">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              :placeholder="$t('system.application.placeholderInput')"
              v-model="params.additionalInformation"
            >
            </el-input>
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button
        type="primary"
        @click="
          loading = true
          handleSubmit()
        "
        :loading="loading"
      >
        {{ $t('common.save') }}
      </el-button>
    </span>
  </x-dialog>
</template>
<script>
  import { cloneDeep, omit, throttle, checkNumber } from '@package/utils'
  import { apiPutEditClient, apiPostAddClient, apiGetClient } from '../api/externalApplication.js'
  import { EnumApiCode } from '../../../../../../globalEnum'

  export default {
    props: {
      dictOptions: {
        type: Object
      }
    },
    data() {
      return {
        visible: false,
        loading: false,
        title: this.$t('system.application.add'),
        params: {
          clientId: '',
          clientName: '',
          clientSecret: '',
          authorizationGrantTypes: [],
          redirectUris: '',
          scopes: '',
          accessTokenValidity: '',
          refreshTokenValidity: '',
          autoapprove: 'true',
          clientSecretExpiresAt: '',
          clientAuthenticationMethods: [],
          state: '1',
          clientImg: '',
          filesList: []
        },
        rules: {
          clientId: [{ required: true, message: this.$t('system.application.placeholderInput'), trigger: 'blur' }],
          clientName: [{ required: true, message: this.$t('system.application.placeholderInput'), trigger: 'blur' }],
          clientSecret: [{ required: true, message: this.$t('system.application.placeholderInput'), trigger: 'blur' }],
          authorizationGrantTypes: [
            { required: true, message: this.$t('system.application.placeholderSelect'), trigger: 'blur' }
          ],
          clientSecretExpiresAt: [
            { required: true, message: this.$t('system.application.placeholderSelect'), trigger: 'blur' }
          ],
          clientAuthenticationMethods: [
            { required: true, message: this.$t('system.application.placeholderSelect'), trigger: 'blur' }
          ],
          scopes: [{ required: true, message: this.$t('system.application.placeholderInput'), trigger: 'blur' }],
          autoapprove: [{ required: true, message: this.$t('system.application.placeholderSelect'), trigger: 'blur' }],
          state: [{ required: true, message: this.$t('system.application.placeholderSelect'), trigger: 'blur' }],
          accessTokenValidity: [
            { required: true, message: this.$t('system.application.placeholderInput'), trigger: 'blur' },
            { required: true, validator: this.validateNumber, trigger: 'blur' }
          ],
          refreshTokenValidity: [{ required: true, validator: this.validateNumber, trigger: 'blur' }]
        }
      }
    },
    methods: {
      handleOpen(info) {
        this.visible = true
        if (info?.id) {
          this.title = this.$t('common.edit')
          apiGetClient(info.clientId).then(({ data }) => {
            this.$nextTick(() => {
              this.params = Object.assign(this.params, cloneDeep(data))
              this.params.authorizationGrantTypes = this.params?.authorizationGrantTypes.split(',') ?? ''
              this.params.clientAuthenticationMethods = this.params?.clientAuthenticationMethods.split(',') ?? ''
              this.params.filesList = this.params.clientImg
                ? [{ fileName: this.params.clientImg.split('?')[0], filePath: this.params.clientImg }]
                : []
              this.params.state += ''
            })
          })
          return
        }
        this.title = this.$t('system.application.add')
      },
      handleSubmit: throttle(function () {
        this.loading = true
        const { fileList } = this.$refs.fileUpload
        this.params.clientImg = fileList.length ? fileList[0].filePath || fileList[0].response.data.filePath : ''
        this.$refs.applicationForm.validate(async (valid) => {
          if (valid) {
            const param = {
              ...this.params,
              authorizationGrantTypes: this.params.authorizationGrantTypes.toString(),
              clientAuthenticationMethods: this.params.clientAuthenticationMethods.toString()
            }
            try {
              const { code, msg } = this.params.id ? await apiPutEditClient(param) : await apiPostAddClient(param)
              this.loading = false
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                this.handleClose()
                this.$emit('handleSuccess')
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.loading = false
            }
          } else {
            this.loading = false
            return false
          }
        })
      }, 1000),
      validateNumber(rule, value, callback) {
        if (value && value !== '' && !checkNumber(value)) {
          callback(new Error(this.$t('system.application.placeholderInputTips')))
        } else {
          callback()
        }
      },
      handleClose() {
        this.params = omit(this.params, 'id')
        this.$refs.applicationForm.resetFields()
        this.params = {
          clientId: '',
          clientName: '',
          clientSecret: '',
          authorizationGrantTypes: [],
          redirectUris: '',
          scopes: '',
          accessTokenValidity: '',
          refreshTokenValidity: '',
          autoapprove: 'true',
          clientSecretExpiresAt: '',
          clientAuthenticationMethods: [],
          state: '1',
          filesList: []
        }
        this.loading = false
        this.visible = false
      }
    }
  }
</script>
